package cn.woowc.through.loader;

import cn.woowc.through.thread.ConsoleStreamRunnable;
import cn.woowc.through.thread.BatThreadFactory;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @version V1.0.0
 * @ClassName: {@link RunBatInitLoader}
 * @Description: Socket 初始化后加载
 * @author: Lanzhou
 * @date: 2021/4/29 17:08
 * @Copyright:2020 All rights reserved.
 */
public class RunBatInitLoader {

    /**
     * 创建Bat文件
     *
     * @param bootPath 模板路径
     * @param order    bat内容
     * @throws IOException
     */
    protected void createRunBat(String bootPath, String order) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream(bootPath);
        FileChannel channel = fileOutputStream.getChannel();
        // 创建一个缓冲区 byteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(order.length());
        // 将str 放入到buffer
        byteBuffer.put(order.getBytes());
        // 对byteBuffer进行反转
        byteBuffer.flip();
        // 将byteBuffer 数据写入到fileChannel
        channel.write(byteBuffer);
        fileOutputStream.close();
    }

    /**
     * 创建运行环境
     *
     * @param envResource 运行文件资源, 对应项目resources下的资源文件
     * @throws IOException
     */
    protected void createRunEnv(String[] envResource) throws IOException {
        for (String resource : envResource) {
            ClassPathResource res = new ClassPathResource(resource);
            // 怎么读取为我们项目运行时的资源目录
            String resourcePath = ResourceUtils.getURL("classpath:").getPath();
            File model = new File(resourcePath + resource);
            if (!model.exists()) {
                FileUtils.copyToFile(res.getInputStream(), model);
            }
        }
    }

    /**
     * 调用bat
     *
     * @param batFilePath
     * @return
     */
    protected String execBat(String batFilePath) {
        Runtime rt = Runtime.getRuntime();
        Process process = null;
        try {
            process = rt.exec(batFilePath);
            //获取进程的标准输入流
            final InputStream inputStream = process.getInputStream();
            //获取进城的错误流
            final InputStream errorStream = process.getErrorStream();
            ExecutorService service = new ThreadPoolExecutor(2, 2,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<>(), new BatThreadFactory());

            //启动两个线程，一个线程负责读标准输出流，另一个负责读标准错误流
            service.submit(new ConsoleStreamRunnable(inputStream, "INFO"));
            service.submit(new ConsoleStreamRunnable(errorStream, "ERROR"));
            service.shutdown();

            process.waitFor();
            process.destroy();
        } catch (Exception e) {
            try {
                assert process != null;
                process.getErrorStream().close();
                process.getInputStream().close();
                process.getOutputStream().close();
            } catch (Exception ee) {
                System.err.println("流关闭失败" + ee);
            }
            return null;
        }
        return "OK";
    }


}
